package mid

import (
	"net/http"
	"os"
	"strconv"
	"strings"

	"gitee.com/firewing_group/model/comm"
	"gitee.com/firewing_group/model/ctxdata"
	"gitee.com/firewing_group/test/utils"
	"github.com/labstack/echo"
)

func UsefulMid(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		cc := c.Get("cc").(*ctxdata.Cusctx)
		if in := c.Request().Header.Get("useful"); in != "" {
			cc.Logf("useful_%v", in)
			segs := strings.Split(in, "___")
			if len(segs) != 2 {
				cc.Errf("u_i_2")
				return c.JSON(http.StatusBadRequest, comm.Bad("有用的控件数量非法", comm.STATUS_COMMON))
			}
			timestr := utils.DecodeString(segs[0])
			if timestr == "" {
				cc.Errf("ts_i")
				return c.JSON(http.StatusBadRequest, comm.Bad("时间控件为空", comm.STATUS_COMMON))
			} else {
				if timestamp, err := strconv.Atoi(timestr); err != nil {
					cc.Errf("ts_fi")
					return c.JSON(http.StatusBadRequest, comm.Bad("时间控件非法", comm.STATUS_COMMON))
				} else {
					if !utils.CheckTimeStamp(int64(timestamp)) {
						cc.Errf("ts_fi")
						return c.JSON(http.StatusBadRequest, comm.Bad("时间控件未校准", comm.STATUS_COMMON))
					}
				}
			}

			useful := utils.DecodeString(segs[1])
			tegs := strings.Split(useful, "_")
			if !(len(tegs) == 2 || len(tegs) == 3) {
				cc.Errf("u_i_%v=%v", segs[1], useful)
				return c.JSON(http.StatusBadRequest, comm.Bad("有用的控件未加载", comm.STATUS_COMMON))
			}

			device := tegs[0]
			country := tegs[1]
			if len(tegs) == 3 {
				channel := tegs[2]
				c.Set("channel", channel)
			}
			cc.Logf("useful_%v", useful)
			cc.Logf("tegs_%v", tegs)
			c.Set("deviceid", device)
			c.Set("country", country)
			c.Set("raw_enc", segs[1])
			return next(c)

		} else { // 找不到 useful header
			if os.Getenv("mode") == "debug" {
				return next(c)
			}
			cc.Errf("UsefulMid_noheader")
			return c.JSON(http.StatusBadRequest, comm.Bad("无用的控件不存在", comm.STATUS_COMMON))
		}

		return next(c)
	}
}
